<template>
  <Dialog v-model="dialogVisible" title="考评员续期" width="800px">
    <el-form
      ref="formRef"
      :model="renewForm"
      :rules="renewRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 考评员信息 -->
      <el-divider content-position="left">考评员信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="考评员姓名">
          {{ evaluatorInfo.evaluatorName || evaluatorInfo.userName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="考评员编码">
          {{ evaluatorInfo.evaluatorCode || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户邮箱">
          {{ evaluatorInfo.userEmail || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户手机">
          {{ evaluatorInfo.userMobile || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="职业名称">
          {{ evaluatorInfo.professionName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="资质等级">
          {{ evaluatorInfo.qualificationLevel || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="证书编号">
          {{ evaluatorInfo.certificateNumber || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusColor(evaluatorInfo.qualificationStatus)">
            {{ getStatusName(evaluatorInfo.qualificationStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="证书有效期" :span="2">
          {{ evaluatorInfo.certificateDate }} 至 {{ evaluatorInfo.validUntil }}
          <el-tag type="warning" style="margin-left: 10px;" v-if="isExpiringSoon">
            即将到期
          </el-tag>
          <el-tag type="danger" style="margin-left: 10px;" v-if="isExpired">
            已到期
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 续期信息 -->
      <el-divider content-position="left">续期信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="续期类型" prop="renewType">
            <el-radio-group v-model="renewForm.renewType">
              <el-radio value="normal">正常续期</el-radio>
              <el-radio value="early">提前续期</el-radio>
              <el-radio value="late">延期续期</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="续期年限" prop="renewYears">
            <el-select v-model="renewForm.renewYears" placeholder="请选择续期年限">
              <el-option label="1年" :value="1" />
              <el-option label="2年" :value="2" />
              <el-option label="3年" :value="3" />
              <el-option label="5年" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="新有效期开始" prop="newValidFrom">
            <el-date-picker
              v-model="renewForm.newValidFrom"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新有效期结束" prop="newValidTo">
            <el-date-picker
              v-model="renewForm.newValidTo"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 培训记录 -->
      <el-divider content-position="left">培训记录</el-divider>
      <el-form-item label="是否需要培训" prop="requireTraining">
        <el-switch v-model="renewForm.requireTraining" />
      </el-form-item>
      
      <div v-if="renewForm.requireTraining">
        <el-form-item label="培训类型" prop="trainingType">
          <el-checkbox-group v-model="renewForm.trainingType">
            <el-checkbox label="annual">年度培训</el-checkbox>
            <el-checkbox label="skill">技能提升培训</el-checkbox>
            <el-checkbox label="regulation">法规培训</el-checkbox>
            <el-checkbox label="assessment">评价方法培训</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="培训学时" prop="trainingHours">
          <el-input-number
            v-model="renewForm.trainingHours"
            :min="8"
            :max="120"
            placeholder="培训学时"
            style="width: 100%"
          />
          <span style="margin-left: 10px; color: #999;">小时</span>
        </el-form-item>
        
        <el-form-item label="培训机构" prop="trainingOrg">
          <el-input v-model="renewForm.trainingOrg" placeholder="请输入培训机构名称" />
        </el-form-item>
        
        <el-form-item label="培训证书" prop="trainingCertificate">
          <el-upload
            :limit="1"
            :auto-upload="false"
            :on-change="handleTrainingCertUpload"
            accept=".jpg,.jpeg,.png,.pdf"
          >
            <el-button type="primary">上传培训证书</el-button>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png/pdf格式，不超过5MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </div>
      
      <!-- 考核记录 -->
      <el-divider content-position="left">考核记录</el-divider>
      <el-form-item label="评价质量评估" prop="qualityAssessment">
        <el-rate
          v-model="renewForm.qualityAssessment"
          :max="5"
          show-text
          :texts="['差', '较差', '一般', '良好', '优秀']"
        />
      </el-form-item>
      
      <el-form-item label="参与评价次数" prop="evaluationCount">
        <el-input-number
          v-model="renewForm.evaluationCount"
          :min="0"
          placeholder="参与评价次数"
          style="width: 100%"
        />
        <span style="margin-left: 10px; color: #999;">次</span>
      </el-form-item>
      
      <el-form-item label="投诉情况" prop="complaintStatus">
        <el-radio-group v-model="renewForm.complaintStatus">
          <el-radio value="none">无投诉</el-radio>
          <el-radio value="minor">轻微投诉已处理</el-radio>
          <el-radio value="major">重大投诉需说明</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item 
        label="投诉说明" 
        prop="complaintDescription" 
        v-if="renewForm.complaintStatus === 'major'"
      >
        <el-input
          v-model="renewForm.complaintDescription"
          type="textarea"
          :rows="3"
          placeholder="请详细说明投诉情况及处理结果"
        />
      </el-form-item>
      
      <!-- 其他信息 -->
      <el-divider content-position="left">其他信息</el-divider>
      <el-form-item label="续期费用" prop="renewFee">
        <el-input-number
          v-model="renewForm.renewFee"
          :min="0"
          :precision="2"
          placeholder="续期费用"
          style="width: 100%"
        />
        <span style="margin-left: 10px; color: #999;">元</span>
      </el-form-item>
      
      <el-form-item label="缴费状态" prop="paymentStatus">
        <el-radio-group v-model="renewForm.paymentStatus">
          <el-radio value="unpaid">未缴费</el-radio>
          <el-radio value="paid">已缴费</el-radio>
          <el-radio value="waived">免缴费</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="续期备注" prop="renewRemark">
        <el-input
          v-model="renewForm.renewRemark"
          type="textarea"
          :rows="3"
          placeholder="请输入续期备注信息"
        />
      </el-form-item>
      
      <!-- 材料清单 -->
      <el-divider content-position="left">材料清单</el-divider>
      <el-checkbox-group v-model="renewForm.requiredMaterials">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-checkbox label="renewal_application">续期申请表</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox label="id_copy">身份证复印件</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox label="original_certificate">原证书复印件</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox label="training_certificate">培训证书</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox label="work_proof">工作证明</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-checkbox label="evaluation_record">评价记录</el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </el-form>
    
    <template #footer>
      <el-button @click="submitRenew" type="primary" :loading="formLoading">确认续期</el-button>
      <el-button @click="previewCertificate" type="success">预览证书</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const evaluatorInfo = ref({
  evaluatorName: '张三',
  evaluatorCode: 'EV202301001',
  idCard: '123456789012345678',
  phone: '13800138000',
  professionNames: '电工、焊工',
  skillLevelNames: '高级、技师',
  certificateNo: 'CERT202301001',
  status: 'active',
  certificateValidFrom: '2021-01-01',
  certificateValidTo: '2024-01-01'
})

const renewForm = ref({
  renewType: 'normal',
  renewYears: 3,
  newValidFrom: '',
  newValidTo: '',
  requireTraining: false,
  trainingType: [] as string[],
  trainingHours: 24,
  trainingOrg: '',
  trainingCertificate: null,
  qualityAssessment: 4,
  evaluationCount: 15,
  complaintStatus: 'none',
  complaintDescription: '',
  renewFee: 200,
  paymentStatus: 'unpaid',
  renewRemark: '',
  requiredMaterials: [] as string[]
})

const renewRules = ref({
  renewType: [{ required: true, message: '请选择续期类型', trigger: 'change' }],
  renewYears: [{ required: true, message: '请选择续期年限', trigger: 'change' }],
  newValidFrom: [{ required: true, message: '请选择新有效期开始日期', trigger: 'change' }],
  trainingType: [
    {
      validator: (rule: any, value: string[], callback: Function) => {
        if (renewForm.value.requireTraining && (!value || value.length === 0)) {
          callback(new Error('需要培训时请至少选择一种培训类型'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  trainingHours: [
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (renewForm.value.requireTraining && !value) {
          callback(new Error('请填写培训学时'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  qualityAssessment: [{ required: true, message: '请进行评价质量评估', trigger: 'change' }],
  evaluationCount: [{ required: true, message: '请填写参与评价次数', trigger: 'blur' }],
  complaintStatus: [{ required: true, message: '请选择投诉情况', trigger: 'change' }],
  paymentStatus: [{ required: true, message: '请选择缴费状态', trigger: 'change' }]
})

// 判断是否即将到期（30天内）
const isExpiringSoon = computed(() => {
  const validTo = new Date(evaluatorInfo.value.certificateValidTo)
  const now = new Date()
  const diffDays = Math.ceil((validTo.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays > 0 && diffDays <= 30
})

// 判断是否已到期
const isExpired = computed(() => {
  const validTo = new Date(evaluatorInfo.value.certificateValidTo)
  const now = new Date()
  return validTo < now
})

// 监听续期年限变化，自动计算结束日期
watch([() => renewForm.value.newValidFrom, () => renewForm.value.renewYears], () => {
  if (renewForm.value.newValidFrom && renewForm.value.renewYears) {
    const startDate = new Date(renewForm.value.newValidFrom)
    const endDate = new Date(startDate)
    endDate.setFullYear(startDate.getFullYear() + renewForm.value.renewYears)
    renewForm.value.newValidTo = endDate.toISOString().split('T')[0]
  }
})

const getStatusName = (status: string) => {
  const statusMap = {
    'active': '有效',
    'inactive': '无效',
    'suspended': '暂停',
    'expired': '已过期'
  }
  return statusMap[status] || status
}

const getStatusColor = (status: string) => {
  const colorMap = {
    'active': 'success',
    'inactive': 'danger',
    'suspended': 'warning',
    'expired': 'danger'
  }
  return colorMap[status] || 'info'
}

const handleTrainingCertUpload = (file: any) => {
  renewForm.value.trainingCertificate = file.raw
}

const submitRenew = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const renewData = {
      evaluatorId: evaluatorInfo.value.evaluatorCode,
      ...renewForm.value
    }
    
    // TODO: 提交续期申请
    console.log('提交考评员续期:', renewData)
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success('考评员续期申请提交成功')
  } finally {
    formLoading.value = false
  }
}

const previewCertificate = () => {
  // TODO: 预览新证书
  ElMessage.info('证书预览功能开发中...')
}

const resetForm = () => {
  renewForm.value = {
    renewType: 'normal',
    renewYears: 3,
    newValidFrom: '',
    newValidTo: '',
    requireTraining: false,
    trainingType: [],
    trainingHours: 24,
    trainingOrg: '',
    trainingCertificate: null,
    qualityAssessment: 4,
    evaluationCount: 15,
    complaintStatus: 'none',
    complaintDescription: '',
    renewFee: 200,
    paymentStatus: 'unpaid',
    renewRemark: '',
    requiredMaterials: []
  }
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = (data?: any) => {
  dialogVisible.value = true
  if (data) {
    Object.assign(evaluatorInfo.value, data)
  }
  resetForm()
  
  // 设置默认的新有效期开始日期为当前证书到期日期
  if (evaluatorInfo.value.certificateValidTo) {
    renewForm.value.newValidFrom = evaluatorInfo.value.certificateValidTo
  }
}

defineExpose({ open })
</script>
